extends IBasicComponent


class_name TileLayerElement
"""
替换角色脚下的Tile属性
"""


@export var node: Node2D = null
@export var tile_map_layer: TileMapLayer = null

@export var source_id: int = -1
@export var atlas_coords: Vector2i = Vector2i(-1, -1)
@export var alternative_tile: int = 0


class TileCell extends Object:
    var coords: Vector2i = Vector2i.ZERO
    var source_id: int = 0
    var atlas_coords: Vector2i = Vector2i.ZERO
    var alternative_tile: int = 0

    func get_cell(tilemap: TileMapLayer, cell: Vector2i) -> void:
        coords = cell
        atlas_coords = tilemap.get_cell_atlas_coords(cell)
        source_id = tilemap.get_cell_source_id(cell)
        alternative_tile = tilemap.get_cell_alternative_tile(cell)

    func set_cell(tilemap: TileMapLayer) -> void:
        tilemap.set_cell(coords, source_id, atlas_coords, alternative_tile)

    func is_equal(tile: TileCell) -> bool:
        return source_id == tile.source_id and atlas_coords == tile.atlas_coords and alternative_tile == tile.alternative_tile


var __replace_cell: TileCell = TileCell.new()
var __last_cell: TileCell = TileCell.new()


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "node": IComponent.find_parent.bind(self, func(x): return x is Node2D, node),
        "tile_map_layer": func(): return tile_map_layer != null,
    }, super.__check_exports())

func replace_cell() -> bool:
    var cell: Vector2i = tile_map_layer.local_to_map(node.global_position)
    if __last_cell.coords == cell:
        return false
    # 恢复上一个Cell
    __last_cell.set_cell(tile_map_layer)
    # 保存当前Cell
    __last_cell.get_cell(tile_map_layer, cell)
    # 设置为需要替换的Cell
    __replace_cell.coords = cell
    __replace_cell.set_cell(tile_map_layer)
    return true

func __prepare() -> void:
    super.__prepare()

    var cell: Vector2i = tile_map_layer.local_to_map(node.global_position)
    __last_cell.get_cell(tile_map_layer, cell)

    __replace_cell.coords = cell
    __replace_cell.source_id = source_id
    __replace_cell.atlas_coords = atlas_coords
    __replace_cell.alternative_tile = alternative_tile
    __replace_cell.set_cell(tile_map_layer)

func _physics_process(delta: float) -> void:
    replace_cell()
